<template>
    <el-dialog title="问卷上传" width="40%" :visible.sync="editDialogVisible">
        <el-form ref="importForm" :model="form" :rules="rules">
            <!--            <el-form-item label="问卷名称" prop="questionnaireName" label-width="120px">-->
            <!--                <el-input v-model="form.questionnaireName"></el-input>-->
            <!--            </el-form-item>-->
            <el-form-item>
                <el-upload drag
                           ref="upload"
                           name="multipartFile"
                           :limit=limitNum
                           :auto-upload="false"
                           accept=".xlsx"
                           :action="baseUrl"
                           :before-upload="beforeUploadFile"
                           :on-change="fileChange"
                           :on-exceed="exceedFile"
                           :on-success="handleSuccess"
                           :on-error="handleError"
                           :file-list="form.files">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传xlsx文件，且不超过10M</div>
                </el-upload>
            </el-form-item>
        </el-form>
        <div slot="footer">
            <el-button size="small" type="primary" @click="uploadFile('importForm')">立即上传
            </el-button>
            <el-button size="small" @click="cancel('importForm')">取消</el-button>
        </div>
    </el-dialog>
</template>

<script>
    import {mapActions} from "vuex";
    import Env from '../../api/env';

    export default {
        name: "QuestionnaireImport",
        data() {
            return {
                limitNum: 1,  // 上传excell时，同时允许上传的最大数
                editDialogVisible: false,
                baseUrl: Env.baseURL + '/questionnaire/upload',
                form: {
                    questionnaireName: '',
                    files: []
                },
                rules: {
                    questionnaireName: [{
                        required: true, message: '请选择资质类型', trigger: 'change'
                    }]
                },
                headers: {'Content-Type': 'multipart/form-data'}
            }
        },
        methods: {
            ...mapActions('questionnaire', [
                'uploadQuestionnaireAct',
                'setCurrentQuestionnaire',
                'getQuestionnaireAct'
            ]),
            open() {
                console.log("importDialog")
                this.editDialogVisible = true;
            },
            // 文件超出个数限制时的钩子
            exceedFile(files, fileList) {
                this.$message.warning(`只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`);
            },
            // 文件状态改变时的钩子
            fileChange(file, fileList) {
                if (this.form.files.length > 0) {
                    this.form.files = [];
                }
                console.log('add file: ', file);
                console.log('current fileList: ', fileList);
                this.form.files.push(file);
                // console.log('add file: ', file);
                // console.log('current fileList: ', fileList);
                // // this.form.files.push(file);
                // util.loadFile(file.raw).then(fileStr => {
                //     this.form.files.push({content: fileStr, name: file.name, uid: file.uid})
                // }).catch(error => {
                //     console.error(error);
                // })
            },
            // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
            beforeUploadFile(file) {
                console.log('before upload');
                console.log(file);
                let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
                let size = file.size / 1024 / 1024;
                if (extension !== 'xlsx') {
                    this.$message.warning('只能上传后缀是.xlsx的文件');
                }
                if (size > 10) {
                    this.$message.warning('文件大小不得超过10M');
                }
            },
            // 文件上传成功时的钩子
            handleSuccess(res, file, fileList) {
                this.$message.success('文件上传成功');
                console.log('result', res);
                let params = {
                    id: res.data.id
                };
                this.getQuestionnaireAct(params).then(result => {
                    this.$router.push({path: '/editor'});
                }).catch(error => {
                    console.error(error);
                })
            },
            // 文件上传失败时的钩子
            handleError(err, file, fileList) {
                this.$message.error('文件上传失败', err);
            },
            uploadFile(importForm) {
                if (this.form.files.length === 0) {
                    this.$message.warning('请上传文件');
                } else {
                    this.$refs.upload.submit();
                    // console.log("form", this.form);
                    // let multipartFile = new FormData();
                    // multipartFile.append('file', this.form.files[0]);
                    // console.log(multipartFile.get('file'));
                    // await this.uploadQuestionnaireAct(multipartFile);
                    this.editDialogVisible = false;
                    //this.form.files = [];
                    this.$refs[importForm].resetFields();
                }
                // this.$refs[importForm].validate().then(async vaild => {
                //     if (vaild) {
                //         if (this.form.files.length === 0) {
                //             this.$message.warning('请上传文件');
                //         } else {
                //             this.$refs.upload.submit();
                //             // console.log("form", this.form);
                //             // let multipartFile = new FormData();
                //             // multipartFile.append('file', this.form.files[0]);
                //             // console.log(multipartFile.get('file'));
                //             // await this.uploadQuestionnaireAct(multipartFile);
                //             this.editDialogVisible = false;
                //             this.$refs[importForm].resetFields();
                //         }
                //     }
                // }).catch(error => {
                //     console.error(error);
                // })
            },
            cancel(importForm) {
                this.editDialogVisible = false;
                //this.form.files = [];
                this.$refs[importForm].resetFields();
            }
        }
    }
</script>

<style scoped>

</style>
